package cn.fintecher.pangolin.service.manage.scheduled;

import cn.fintecher.pangolin.entity.elastic.SystemLog;
import cn.fintecher.pangolin.entity.elastic.SystemLoginLog;
import cn.fintecher.pangolin.service.manage.elastic.SystemLogElastic;
import cn.fintecher.pangolin.service.manage.elastic.SystemLoginLogElastic;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Auther: xiaqun
 * @Description: 系统日志删除调度
 * @Date: 11:29 2019/9/25
 */

@Component
@EnableScheduling
public class SystemLogScheduled {
    private static final Logger log = LoggerFactory.getLogger(SystemLogScheduled.class);

    @Autowired
    private SystemLogElastic systemLogElastic;

    @Autowired
    private SystemLoginLogElastic systemLoginLogElastic;

    /**
     * 删除2周前日志
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteSystemLog() {
        log.info("删除系统日志调度开始..........");
        DateTime dateTime = new DateTime(new Date());
        Date date = dateTime.minusDays(7).toDate();
        BoolQueryBuilder builder1 = new BoolQueryBuilder();
        builder1.must(QueryBuilders.rangeQuery("operateTime").lt(date.getTime()));
        Iterable<SystemLog> iterable1 = systemLogElastic.search(builder1);
        systemLogElastic.deleteAll(iterable1);

        BoolQueryBuilder builder2 = new BoolQueryBuilder();
        builder2.must(QueryBuilders.rangeQuery("loginTime").lt(date.getTime()));
        Iterable<SystemLoginLog> iterable2 = systemLoginLogElastic.search(builder2);
        systemLoginLogElastic.deleteAll(iterable2);
    }
}
